package org.wejde.muel;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * This class contains the members and methods for sending
 * events to a logging server via UDP.
 * 
 * The methods include establishing the UDP connection and
 * submitting the event to the UDP server.
 * 
 * @author Eric Martin
 * @author Webb Pinner
 *
 */
public class udpLogClient implements Runnable {

	/**
	 * The name of the UDP server.
	 */
	private String server;

	/**
	 * The network port of the UDP server.
	 */
	private int port;
	
	/**
	 * Socket object, needed to connect to a server.
	 */
	private DatagramSocket socket;

	/**
	 * InetAddress object, needed to connect to a server.
	 */
	private InetAddress address;
	
	/**
	 * Flag used to control the "run" method.
	 */
	private boolean runFlag;
	
	Thread runner;
	
	// Constants
	final static private int buflength = 1024;
	
	/**
	 * Constructor method.
	 */
	public udpLogClient(String server, int port){
		this.runFlag = true;
		
		this.server = server;
		this.port = port;
		
		try {
			this.socket = new DatagramSocket();
			this.address = InetAddress.getByName(this.server);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (this.runner == null) {
//			this.runner = new Thread(this);
//			this.runner.start();
		}
		
	}
	
	/**
	 * De-constructor method.
	 */
	public void destroy() {
		this.runFlag = false;
	}

	/**
	 * Submit the event text to the UDP server.
	 * 
	 * @param msg the event text.
	 */
	public void submitEvent(String msg) {
		// DEBUG
		//System.err.print("UDP Log: " + msg);
		
		try {
			// Encode Data
			byte[] buf = new byte[buflength];
			buf = new String(msg).getBytes();

			// Transmit Data
			DatagramPacket packet = new DatagramPacket(buf, buf.length,
					this.address, this.port);
			this.socket.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Method required as part of the Runnable interface.
	 */
	@Override
	public void run() {
		
		while(this.runFlag) {
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
